package opsControllers

import (
	"fmt"
	"lazyops_go/models"
	"lazyops_go/tools"
	"regexp"
	"strings"
)


type SmbUser struct {
	Id 				int				`gorm:"primary_key"`
	User			string			`gorm:"not null;unique"`
	PermsDir		string			`gorm:"type:text"`
}

func (c *OpsController) IndexSmb() {
	cur_user_menus := c.GetSession("cur_user_menus")
	cur_user := c.GetSession("cur_user")

	dict_obj, _ := models.QueryDictKey("SMB_HOST")
	smb_host := dict_obj.DictVal

	cmd_u := "for i in `cat /etc/passwd | awk -F : '{if ($3>1000) print $1}'`;do echo '###'; id $i;done"
	users := tools.SaltRunArgRet(smb_host,"cmd.run",cmd_u,"root")

	smb_user_list := []SmbUser{}
	N :=1
	for _,v  :=range strings.Split(users,"###"){
		smb_user := SmbUser{}
		user_str := strings.Replace(v,","," ",-1)
		user_info := strings.Split(user_str," ")
		user := user_info[0]
		user_group := user_info[1:]
		user_info_list := strings.Split(strings.Split(user," ")[0],"(")
		if (len(user_info_list) ==2){
			user:=strings.Replace(user_info_list[1],")","",-1)
			smb_user.Id = N
			smb_user.User = user
			N+=1
		}
		var g_list_str string
		for _,k := range user_group{
			A_str := strings.Split(k,"(")[1]
			group := strings.Replace(A_str,")","",-1)
			g_list_str += group+","
		}

		if len(g_list_str)>0{
			smb_user.PermsDir = strings.Trim(g_list_str,",")
			smb_user_list = append(smb_user_list, smb_user)
		}
	}

	c.Data["data_list"] = smb_user_list
	c.Data["cur_user"] = cur_user
	c.Data["cur_user_menus"] = cur_user_menus
	c.Data["label"] = "SMB 管理"
	c.XSRFExpire = 7200
	c.Data["xsrf_token"] = c.XSRFToken()
	c.Layout = "base/base.html"
	c.LayoutSections = make(map[string]string)
	c.LayoutSections["Scripts"] = "ops/smbjs.html"
	c.TplName = "ops/smb.html"
}


func (c *OpsController)  AddSmbUser() {
	username := c.GetString("username")
	passwd := c.GetString("passwd")
	// 获取samba服务器IP
	dict_obj, _ := models.QueryDictKey("SMB_HOST")
	smb_host := dict_obj.DictVal
	// 执行命令
	run_cmd := fmt.Sprintf("useradd -s /bin/false %s ;(echo '%s';echo '%s')|smbpasswd -a -s %s",username,passwd,passwd,username)
	tools.SaltRunArgRet(smb_host,"cmd.run",run_cmd,"root")
	c.Data["json"] = "用户已添加"
	c.ServeJSON()
}


func (c *OpsController) GetPerms() {
	cur_perms := c.GetString("cur_perms")
	cur_perm_list := strings.Split(cur_perms,",")

	dict_obj, _ := models.QueryDictKey("SMB_HOST")
	smb_host := dict_obj.DictVal

	cmd_g := `cat /etc/group | awk -F : '{if ($3>1000) print $1}' | grep -E '(^p[0-9]|PNG|public|painting)'|sort`
	groups := tools.SaltRunArgRet(smb_host,"cmd.run",cmd_g,"root")
	group_list := strings.Split(groups,"\n")

	// 生成ztree 数据
	var ztree_data_list []models.ZtreeDate

	prj_data :=models.QueryPrjAll()
	K := 1
	for _,p :=range prj_data{
		var ztr_head models.ZtreeDate
		prj_name := p.PrjName

		ztr_head.Id = K
		ztr_head.Pid = 0
		ztr_head.Name = prj_name
		ztr_head.Open = true
		ztr_head.Checked = true
		ztree_data_list = append(ztree_data_list, ztr_head)
		N := 1
		for _,v :=range group_list{
			re :=regexp.MustCompile(fmt.Sprintf("%s|PNG|public|painting",prj_name))
			if (re.MatchString(v)){
				ztr_head.Id = N+1000
				ztr_head.Pid = K
				ztr_head.Name = v
				ztr_head.Open = true
				ztr_head.Checked = false
				// 判断已存在的属组，默认选中
				for _,k := range cur_perm_list{
					if (v==strings.Trim(k,"\n")){
						ztr_head.Checked = true
					}
				}
				ztree_data_list = append(ztree_data_list, ztr_head)
				N+=1
			}
		}
		K+=1
	}

	c.Data["json"] = ztree_data_list
	c.ServeJSON()
}

func (c *OpsController)  SetPerms() {

	cur_user := c.GetString("cur_user")
	perms_str := c.GetString("perms_list")
	fmt.Println(perms_str)

	// 先清除已有归属
	clean_perm_cmd := fmt.Sprintf("usermod -G %s %s",cur_user,cur_user)

	// 生成设置属组命令
	var set_perms_cmd string
	for _,v :=range strings.Split(perms_str,","){
		if len(v) >=2{
			set_perms_cmd += fmt.Sprintf("usermod -a -G %s %s;",v,cur_user)
		}
	}
	// 获取samba服务器IP
	dict_obj, _ := models.QueryDictKey("SMB_HOST")
	smb_host := dict_obj.DictVal
	// 执行命令
	run_cmd := fmt.Sprintf("%s && %s /bin/systemctl reload smb.service",clean_perm_cmd,set_perms_cmd)
	tools.SaltRunArgRet(smb_host,"cmd.run",run_cmd,"root")
	c.Data["json"] = "设置成功"
	c.ServeJSON()
}

func (c *OpsController)  ChangePasswd() {
	cur_user := c.GetString("cur_user")
	new_passwd := c.GetString("new_passwd")

	// 获取samba服务器IP
	dict_obj, _ := models.QueryDictKey("SMB_HOST")
	smb_host := dict_obj.DictVal
	// 执行命令
	run_cmd := fmt.Sprintf("(echo '%s';echo '%s')|smbpasswd -a -s %s",new_passwd,new_passwd,cur_user)
	tools.SaltRunArgRet(smb_host,"cmd.run",run_cmd,"root")
	c.Data["json"] = "密码已修改"
	c.ServeJSON()
}

func (c *OpsController)  DelSmbUser() {
	cur_user := c.GetString("cur_user")

	// 获取samba服务器IP
	dict_obj, _ := models.QueryDictKey("SMB_HOST")
	smb_host := dict_obj.DictVal
	// 执行命令
	run_cmd := fmt.Sprintf("smbpasswd -x %s;userdel -r %s",cur_user,cur_user)
	tools.SaltRunArgRet(smb_host,"cmd.run",run_cmd,"root")

	c.Data["json"] = "用户已删除"
	c.ServeJSON()
}